package com.hx.interview;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author MinghuaChen
 * @date 2022-02-28 21:36
 * @description 将一个目录下所有TXT文档内的单词出现频次倒库输出到文件
 * 代码可运行，注意代码质量；10分
 */
public class CountWords {
    public static void main(String[] args) {
        File file = new File("D://a.txt");
        FileReader reader = null;

        try {
            reader = new FileReader(file);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("打开文件异常", e);
        }

        BufferedReader bufferedReader = new BufferedReader(reader);
        String readString = null;
        Map<String, Integer> countMap = new HashMap<>();

        try {
            while ((readString = bufferedReader.readLine()) != null) {
                String[] arrays = readString.split(" ");
                for (String each : arrays) {
                    // 去除空串
                    if ("".equals(each.trim())) {
                        continue;
                    }
                    if (countMap.containsKey(each)) {
                        countMap.put(each, countMap.get(each) + 1);
                    } else {
                        countMap.put(each, 1);
                    }
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("读取文件出现异常", e);
        }

        try {
            bufferedReader.close();
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException("关闭读取文件流出现异常", e);
        }


        File targetFile = new File("D://b.txt");
        FileWriter fileWriter = null;

        try {
            fileWriter = new FileWriter(targetFile);
        } catch (IOException e) {
            throw new RuntimeException("创建输出文件出现异常", e);
        }

        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        for (Map.Entry<String, Integer> each : countMap.entrySet()) {
            String tmp = each.getKey() + " " + each.getValue();
            try {
                bufferedWriter.write(tmp);
                bufferedWriter.write("\r\n");
            } catch (IOException e) {
                throw new RuntimeException("写入文件时出现异常", e);
            }
        }
        try {
            // 刷盘
            bufferedWriter.flush();
            // 关闭流
            bufferedWriter.close();
            bufferedWriter.close();
        } catch (IOException e) {
            throw new RuntimeException("关闭输出文件流出现异常", e);
        }

    }
}
